<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="closeDialog"
  >
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
        <el-form
          :model="dataList"
          :rules="dataRule"
          ref="dataList"
          @keyup.enter.native="dataFormSubmit()"
          label-width="80px"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="dataList.name" placeholder="名称"></el-input>
          </el-form-item>
          <el-form-item label="规格" prop="standard">
            <el-input v-model="dataList.standard" placeholder="规格"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unitName">
            <el-select
              v-model="dataList.unitName"
              filterable
              allow-create
              default-first-option
              placeholder="请选择单位"
              @change="change($event)"
            >
              <el-option
                v-for="item in options1"
                :key="item.id"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="型号" prop="model">
            <el-input v-model="dataList.model" placeholder="型号"></el-input>
          </el-form-item>
          <!-- <el-form-item label="颜色" prop="color">
            <el-input v-model="dataList.color" placeholder="颜色"></el-input>
          </el-form-item> -->
          <el-form-item label="类别" prop="categoryName">
            <el-cascader
              ref="refSubCat"
              v-model="dataList.categoryId"
              :options="options"
              placeholder="请选择"
              :props="{ checkStrictly: true, value: 'id', label: 'text' }"
              @change="handlechange(value)"
              @getCheckedNodes="getCheckedNodes"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="序列号" prop="enableSerialNumber">
            <el-select
              v-model="dataList.enableSerialNumber"
              filterable
              allow-create
              default-first-option
              placeholder="请选择序列号"
              @change="change($event)"
            >
              <el-option
                v-for="item in options2"
                :key="item.id"
                :label="item.label"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="安全存量" prop="safetyStock">
            <el-input
              v-model="dataList.safetyStock"
              placeholder="安全存量"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-form
          :model="dataForm"
          ref="dataForm"
          :rules="dataRule1"
          @keyup.enter.native="dataFormSubmit()"
          label-width="80px"
        >
          <el-form-item
            label="条码"
            prop="BarCode"
            :class="{ 'is-required': !dataForm.id }"
          >
            <!-- 
                 
          -->
            <el-input
              v-model="dataForm.BarCode"
              placeholder="条码"
              onkeyup="value=value.replace(/[^\d]/g, '').replace(/^0{1,}/g,'')"
            ></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="CommodityUnit">
            <el-input
              v-model="dataForm.CommodityUnit"
              placeholder="单位"
            ></el-input>
          </el-form-item>
          <el-form-item label="采购价" prop="PurchaseDecimal">
            <el-input
              v-model="dataForm.PurchaseDecimal"
              placeholder="采购价"
            ></el-input>
          </el-form-item>
          <el-form-item label="零售价" prop="WholesaleDecimal">
            <el-input
              v-model="dataForm.WholesaleDecimal"
              placeholder="零售价"
            ></el-input>
          </el-form-item>
          <el-form-item label="销售价" prop="CommodityDecimal">
            <el-input
              v-model="dataForm.CommodityDecimal"
              placeholder="销售价"
            ></el-input>
          </el-form-item>
          <el-form-item label="最低销售价" prop="LowDecimal">
            <el-input
              v-model="dataForm.LowDecimal"
              placeholder="最低销售价"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="扩展信息" name="second">
        <el-form
          :model="dataList"
          @keyup.enter.native="dataFormSubmit()"
          label-width="80px"
        >
          <el-form-item label="制造商" prop="mfrs">
            <el-input v-model="dataList.mfrs" placeholder="制造商"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="初始库存" name="third">
        <el-form
          ref="dataStock"
          @keyup.enter.native="dataFormSubmit()"
          label-width="80px"
        >
          <template v-for="(val, ind) in dataStock">
            <el-form-item :label="val.name" :key="ind">
              <el-input v-model="val.stock"></el-input>
            </el-form-item>
          </template>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :disabled="btnstatus"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      btnstatus: false,
      visible: false,
      activeName: "first",
      dataForm: {
        id: 0,
        DepotName: "",
        name: "",
        standard: "",
        materialOther: "",
        materialOther: "",
        unitName: "",
        purchaseDecimal: "",
        wholesaleDecimal: "",
        commodityDecimal: "",
        lowDecimal: "",
        mfrs: "",
        BarCode: "",
        CommodityUnit: "",
      },
      sortListId: "",
      dataList: {
        name: "",
        standard: "",
        model: "",
        categoryId: "",
        enableSerialNumber: "",
        safetyStock: "",
        unitName: "",
        categoryName: "",
        mfrs: "",
      },
      dataStock: [],
      options: [],
      options1: [],
      options2: [
        {
          value: "0",
          label: "无",
        },
        {
          value: "1",
          label: "有",
        },
      ],
      value: null,
      value1: null,
      label: null,
      Unit: "",
      manyUnit: "",
      dataRule: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      },
      dataRule1: {
        BarCode: [
          { required: true, message: "条码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 获取分类的下拉框
    getCategory() {
      this.$http({
        url: this.$http.adornUrl(
          "/materialCategory/getMaterialCategoryTree?id="
        ),
        method: "post",
      }).then(({ data }) => {
        console.log("成功获取到菜单数据...", data.data);
        this.options = this.getTreeData(data.data);
      });
    },
        // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    init(index, id, pageIndex, pageSize, mfrs) {
      console.log(index, id, pageIndex, pageSize, mfrs);
      this.getCategory();
      this.dataForm.id = id || 0;
      this.visible = true;
      let str = `{"name":""}`;
      var search = encodeURIComponent(str);
      this.$http({
        url: this.$http.adornUrl(`/unit/list?search=${search}`),
        method: "get",
        params: this.$http.adornParams(
          {
            currentPage: 1,
            pageSize: 1000,
          },
          false
        ),
      }).then((data) => {
        console.log(data.data.data.list);
        this.options1 = data.data.data.list;
      });
      this.$nextTick(() => {
        if (this.dataForm.id) {
          console.log(111);
          let str = `{"barCode":"","name":"","standard":"","endavailableStock":"","beginavailableStock":"","beginstock":"","endstock":"","model":"","categoryIds":"","mpList":"规格,颜色,制造商"}`;
          var search = encodeURIComponent(str);
          this.$http({
            url: this.$http.adornUrl(`/material/list?search=${search}`),
            method: "get",
            params: this.$http.adornParams({
              currentPage: pageIndex,
              pageSize: pageSize,
            }),
          })
            .then(({ data }) => {
              // console.log(index)
              console.log(data.data.list[index]);
              if (data && data.code === 0) {
                this.dataList = data.data.list[index];
                console.log(this.dataList.BarCode);
                console.log(typeof this.dataList.BarCode);
                this.dataList.enableSerialNumber =
                  data.data.list[index].enableSerialNumber == 0 ? "无" : "有";
                console.log(mfrs, this.dataForm.mfrs);
              }
            })
            .then(() => {
              this.$http({
                url: this.$http.adornUrl(`/materialsExtend/getDetailList`),
                method: "get",
                params: {
                  materialId: id,
                },
              }).then(({ data }) => {
                console.log(data.data.rows[0]);
                if (data && data.code === 0) {
                  this.dataForm = data.data.rows[0];
                  this.sortListId = data.data.rows[0].Id;
                  this.dataForm.id = id;
                  this.dataForm.BarCode = Number(data.data.rows[0].BarCode);
                }
              });
            })
            .then(() => {
              this.$http({
                url: this.$http.adornUrl(`/depot/getAllListWithStock`),
                method: "get",
                params: {
                  mId: id,
                },
              }).then(({ data }) => {
                // console.log(data.data)
                if (data && data.code == 0) {
                  this.dataStock = data.data;
                }
              });
            })
            .then(() => {
              this.$http({
                url: this.$http.adornUrl(
                  "/materialCategory/getMaterialCategoryTree?id="
                ),
                method: "post",
              }).then(({ data }) => {
                console.log("成功获取到菜单数据...", data.data);
                this.options = data.data;
              });
            });
        } else {
          console.log(222);
          this.$http({
            url: this.$http.adornUrl(`/depot/getAllListWithStock?mId=0`),
            method: "get",
          }).then((data) => {
            console.log(data.data.data);
            if (data.data.code == 0) {
              this.dataStock = data.data.data;
            }
          });
        }
      });
    },
    handlechange(value) {
      // console.log(this.$refs["refSubCat"].getCheckedNodes()[0].value);
      // console.log(this.$refs["refSubCat"].getCheckedNodes()[0].label);
      this.value1 = this.$refs["refSubCat"].getCheckedNodes()[0].value;
      this.label = this.$refs["refSubCat"].getCheckedNodes()[0].label;
    },
    getCheckedNodes(value) {
      console.log(value);
    },
    change(e) {
      console.log(e);
      console.log(typeof e);
      if (typeof e == "string") {
        this.Unit = e;
        this.$http(
          {
            url: this.$http.adornUrl(`/material/checkIsExist`),
            method: "get",
            params: this.$http.adornParams({
              id: this.dataForm.id,
              name: this.dataList.name,
              model: this.dataList.model,
              color: this.dataList.unitName,
              standard: this.dataList.standard,
              mfrs: this.dataList.mfrs,
              otherField1: "",
              otherField2: "",
              otherField3: "",
              unit: this.dataList.unitName,
              unitId: "",
            }),
          },
          false
        ).then((data) => {
          console.log(data);
          if (data.data.status == false) {
            this.$message({
              message: "操作失败，请检查信息",
              type: "error",
              duration: 1500,
            });
          }
        });
      } else {
        this.manyUnit = e.id;
      }
    },
    closeDialog() {
      this.dataForm = {
        id: 0,
        DepotName: "",
        name: "",
        standard: "",
        materialOther: "",
        materialOther: "",
        unitName: "",
        purchaseDecimal: "",
        wholesaleDecimal: "",
        commodityDecimal: "",
        lowDecimal: "",
        mfrs: "",
        BarCode: "",
        CommodityUnit: "",
      };

      this.dataList = {
        name: "",
        standard: "",
        model: "",
        categoryId: "",
        enableSerialNumber: "",
        safetyStock: "",
        unitName: "",
        categoryName: "",
        mfrs: "",
      };
      this.dataList.enableSerialNumber=""
      this.dataStock = [];
      this.btnstatus=false;
    },
    // 表单提交
    dataFormSubmit() {
      let inServFormvalid = null;
      let dataFormvalid = null;
      this.$refs["dataList"].validate((valid1) => {
        inServFormvalid = valid1;

        this.$refs["dataForm"].validate((valid2) => {
          dataFormvalid = valid2;
        });
      });
      if (inServFormvalid && dataFormvalid) {
        console.log(this.dataForm.name);
        // 编辑
        if (this.dataForm.id) {
          let info = {
            Name: this.dataList.name,
            Standard: this.dataList.standard,
            Unit: this.Unit,
            manyUnit: this.manyUnit,
            Model: this.dataList.model,
            Color: "",
            parentName: this.label,
            parentId: this.value1,
            EnableSerialNumber: (this.dataList.enableSerialNumber =
              this.dataList.enableSerialNumber == "无" ? "0" : "1"),
            SafetyStock: this.dataList.safetyStock,
            Remark: "",
            Mfrs: this.dataList.mfrs,
            OtherField1: "",
            OtherField2: "",
            OtherField3: "",
            UnitId: this.manyUnit,
            CategoryId: this.value1,
            sortList: [{ id: this.sortListId, defaultFlag: 1 }],
            inserted: [],
            deleted: [],
            updated: [
              {
                PurchaseDecimal: this.dataForm.PurchaseDecimal,
                LowDecimal: this.dataForm.LowDecimal,
                BarCode: this.dataForm.BarCode,
                Id: this.sortListId,
                CommodityUnit: this.dataForm.CommodityUnit,
                WholesaleDecimal: this.dataForm.WholesaleDecimal,
                CommodityDecimal: this.dataForm.CommodityDecimal,
                _selected: true,
              },
            ],
            stock: `[${this.dataStock
              .map((iitem) => {
                console.log(iitem);
                return `{"depotId":${iitem.id},"number":${iitem.stock}},`;
              })
              .join("")}]`,
          };
          this.$http({
            url: this.$http.adornUrl(`/material/update?id=${this.dataForm.id}`),
            method: "post",
            data: this.$http.adornData(info, false),
          }).then((data) => {
            // console.log(data);
            if (data.data && data.data.code === 0) {
              this.btnstatus = true;
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
        // 增加
        else {
          console.log(111);
          let info = {
            Name: this.dataList.name,
            Standard: this.dataList.standard,
            Unit: this.Unit,
            manyUnit: this.manyUnit,
            Model: this.dataList.model,
            Color: "",
            parentName: this.label,
            parentId: this.value1,
            EnableSerialNumber: (this.dataList.enableSerialNumber =
              this.dataList.enableSerialNumber == "无" ? "0" : "1"),
            SafetyStock: this.dataList.safetyStock,
            Remark: "",
            Mfrs: this.dataList.mfrs,
            OtherField1: "",
            OtherField2: "",
            OtherField3: "",
            UnitId: this.manyUnit,
            CategoryId: this.value1,
            sortList: [{ id: this.sortListId, defaultFlag: 1 }],
            inserted: [
              {
                BarCode: this.dataForm.BarCode,
                CommodityUnit: this.dataForm.CommodityUnit,
                PurchaseDecimal: this.dataForm.PurchaseDecimal,
                CommodityDecimal: this.dataForm.CommodityDecimal,
                WholesaleDecimal: this.dataForm.WholesaleDecimal,
                LowDecimal: this.dataForm.LowDecimal,
              },
            ],
            deleted: [],
            updated: [
              {
                PurchaseDecimal: this.dataForm.PurchaseDecimal,
                LowDecimal: this.dataForm.LowDecimal,
                BarCode: this.dataForm.BarCode,
                Id: this.sortListId,
                CommodityUnit: this.dataForm.CommodityUnit,
                WholesaleDecimal: this.dataForm.WholesaleDecimal,
                CommodityDecimal: this.dataForm.CommodityDecimal,
                _selected: true,
              },
            ],
            stock: `[${this.dataStock
              .map((iitem) => {
                console.log(iitem);
                return `{"depotId":${iitem.id},"number":${iitem.stock}},`;
              })
              .join("")}]`,
          };
          this.$http({
            url: this.$http.adornUrl(`/material/add`),
            method: "post",
            data: this.$http.adornData(info, false),
          }).then((data) => {
            // console.log(data);
            if (data.data && data.data.code === 0) {
              this.btnstatus = true;
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      }
    },
  },
};
</script>
